[Console]::OutputEncoding = [System.Text.Encoding]::UTF8

# home
# Set-Location ~

# module: posh-git config
# 使用posh-git会使得仓库文件夹内的Set-Location操作变慢
# posh-git的GitPromptSettings变多或者逻辑耗时变多，会使用Set-Location更慢
# 所以可以把不需要的设置设为空，来提高速度
$poshGitModule = Get-Module posh-git -ListAvailable | Sort-Object Version -Descending | Select-Object -First 1
if ($poshGitModule) {
  Import-Module posh-git
  $GitPromptSettings.WindowTitle = ""
  $GitPromptSettings.ShowStatusWhenZero = $false
  $GitPromptSettings.PathStatusSeparator.Text = ""
  $GitPromptSettings.DefaultPromptPath.ForegroundColor = [ConsoleColor]::Cyan
  $GitPromptSettings.DefaultPromptSuffix.Text = "$([char]0x203A) " # chevron unicode symbol
  $GitPromptSettings.DefaultPromptSuffix.ForegroundColor = [ConsoleColor]::Magenta
  # 使用主题：https://github.com/dracula/powershell
  $GitPromptSettings.BeforeStatus.ForegroundColor = [ConsoleColor]::Magenta
  $GitPromptSettings.BranchColor.ForegroundColor = [ConsoleColor]::Magenta
  $GitPromptSettings.AfterStatus.ForegroundColor = [ConsoleColor]::Magenta
}
else {
  Write-Warning "could not find posh-git module, please install it by next command and reload pwsh`nInstall-Module posh-git -Scope CurrentUser -AllowPrerelease -Force"
}

# module: PSReadline config
# Set-PSReadLineKeyHandler
Set-PSReadLineKeyHandler -Key Ctrl+. -Function MenuComplete
# Optimize PSReadline history
# Optimize-PSReadlineHistory -MaximumCommandCount 222 -Passthru

# concfg tokencolor enable
try { $null = Get-Command concfg -ea stop; concfg.ps1 tokencolor -n enable } catch { }

#region aliases
#Set-Alias code code-insiders

Remove-Item 'Alias:\cat' -Force
Set-Alias cat Get-ContentWithLineNumbers

if (Get-Module PSGitUtils -ListAvailable) {
  Import-Module PSGitUtils
  $GitUtilsConfig.Type = $false

  Set-Alias ga gga
  Set-Alias gb ggb
  Set-Alias gck ggck
  Remove-Item 'Alias:\gcm' -Force
  Set-Alias gcm ggc
  Set-Alias gcmd Get-Command
  Set-Alias gd ggd
  Set-Alias gh ggl
  Set-Alias gpl ggpl
  Remove-Item 'Alias:\gps' -Force
  Set-Alias gps ggps
  Set-Alias grst ggrst
  Set-Alias gs ggs
}

#endregion


## search sth. with bing
function Bing {
  param (
    $key
  )

  $url = "http://www.bing.com/search?q=" + $key

  Start-Process $url
}

## use bat instead of cat
function Get-ContentWithLineNumbers {
  <#
  .EXAMPLE
  Get-ContentWithLineNumbers ./hello.txt,./world.txt -NoLineNumber
  #>
  [CmdletBinding()]
  param (
    [Parameter(Mandatory = $true)]
    [string[]]$Path,
    [switch]$NoLineNumber
  )

  if (Get-Command bat -errorAction SilentlyContinue) {
    if ($NoLineNumber) {
      Get-Content $Path
    }
    else {
      bat.ps1 $Path
    }
  }
  else {
    Get-Content $Path
  }
}

## 设置控制台提示风格，支持风格：C|Default
function Set-Prompt {
  [CmdletBinding()]
  param(
    # [Parameter(Mandatory = $true, HelpMessage = "select one from [C, Default]")]
    [ValidateSet('Simple', 'Default', IgnoreCase = $true)]
    $Mode
  )

  $varPSPromptMode = (Get-Variable 'PSPromptMode'  -ea SilentlyContinue)

  #配置变量不存在则新建
  if ($null -eq $varPSPromptMode) {
    New-Variable -Name 'PSPromptMode' -Value $Mode -Scope 'Global'
    $varPSPromptMode = Get-Variable -Name 'PSPromptMode'

    $varPSPromptMode.Description = '提示函数配置变量'

    #限制配置变量的取值集合
    $varPSPromptModeAtt = New-Object System.Management.Automation.ValidateSetAttribute('Simple', 'Default')
    $varPSPromptMode.Attributes.Add($varPSPromptModeAtt)

    #限制配置变量为只读并且可以贯穿所有作用域ls
    $varPSPromptMode.Options = 'ReadOnly, AllScope'
  }
  else {
    if ($null -eq $Mode) {
      [string]$title = "Set Prompt Style"
      [string]$message = "select a mode to set the prompt style"
      $simple = New-Object System.Management.Automation.Host.ChoiceDescription "&Simple", "just show the directory name"
      $default = New-Object System.Management.Automation.Host.ChoiceDescription "&Default", "default powershell prompt style"
      $options = [System.Management.Automation.Host.ChoiceDescription[]] ($simple, $default)

      $chooseIndex = $Host.UI.PromptForChoice($title, $message, $options, 0)

      if ($chooseIndex -eq 1) {
        $Mode = 'Default'
      }
      else {
        $Mode = 'Simple'
      }
    }

    #更新配置
    #只读变量可以通过-force选项更新值
    Set-Variable -Name PSPromptMode -Value $Mode -Force
  }
}

## 默认控制台提示执行函数
function Prompt() {
  switch ($PSPromptMode) {
    'simple' {
      $color = 'DarkMagenta'
      $prompt = ''
      $location = $executionContext.SessionState.Path.CurrentLocation.Path

      if ($location -eq $HOME) {
        $prompt = "~"
      }
      else {
        $arr = $location.Split("\")
        $length = $arr.Length
        if ($length -eq 2 -and $arr[1] -eq "") {
          $prompt = $arr[0]
        }
        elseif ($location.EndsWith("\")) {
          # 注册表 $location 是以 \ 结尾的
          $prompt = $arr[$length - 2]
        }
        else {
          $prompt = $arr[$length - 1]
        }
      }

      if ($poshGitModule) {
        $GitPromptSettings.DefaultPromptPath.Text = "$($prompt) "
        & $GitPromptScriptBlock
      }
      else {
        $action = Write-Host $prompt -NoNewLine -ForegroundColor $color
        $action += Write-Host "$("$([char]0x203A)" * ($nestedPromptLevel + 1))" -NoNewLine -ForegroundColor $color
        "$action "
      }

    }
    default {
      if ($poshGitModule) {
        $GitPromptSettings.DefaultPromptPath.Text = "$(Get-PromptPath) "
        & $GitPromptScriptBlock
      }
      else {
        $action = "PS $($executionContext.SessionState.Path.CurrentLocation)$('>' * ($nestedPromptLevel + 1))"
        "$action "
      }
    }
  }
}

Set-Prompt Simple
